package com.example.neteasecloudmusic_kotlin.logic

import android.util.Log
import androidx.lifecycle.liveData
import com.example.neteasecloudmusic_kotlin.logic.network.NetEaseMusicNetwork
import kotlinx.coroutines.Dispatchers
import java.lang.Exception
import java.lang.RuntimeException
import kotlin.coroutines.CoroutineContext

object Repository {

    fun getPlayListInfo() = fire(Dispatchers.IO) {
        val playListResponse = NetEaseMusicNetwork.getPlayListInfo()
        if (playListResponse != null) {
            Result.success(playListResponse)
        } else {
            Result.failure(RuntimeException("网络请求歌单出错！"))
        }
    }

    fun refreshHomePage() = fire(Dispatchers.IO) {
        val homePageResponse = NetEaseMusicNetwork.getHomePageInfo()
        if (homePageResponse != null) {
            Result.success(homePageResponse)
        } else {
            Result.failure(RuntimeException("网络请求主页面出错！"))
        }
    }

    private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) = liveData<Result<T>>(context) {
        val result = try {
            block()
        } catch (e: Exception) {
            Result.failure<T>(e)
        }
        emit(result)
    }


}